﻿// ===============================================================================
// XCI.Parent 西安交通信息WinForm开发框架 2019 版权所有
// ===============================================================================

using DevExpress.XtraBars;
using DevExpress.XtraBars.Docking2010.Views;
using DevExpress.XtraNavBar;
using DevExpress.XtraTreeList;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using XCI.Helper;
using XCI.Sys.Helper;
using XCI.Sys.Model;
using XCI.Sys.Service;
using XCI.Windows.Forms;
using XCI.Windows.Helper;

namespace XCI.Sys.Forms
{
    public partial class FrmStandardMain : FrmBase
    {
        private bool _isExitSystem;

        /// <summary>
        /// 模块操作类
        /// </summary>
        private ModuleHelper moduleHelper;

        public FrmStandardMain()
        {
            InitializeComponent();

            SetStyle(ControlStyles.DoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint, true);
            WinHelper.SetImageListSize(SysRuntime.Setting.NavMenuLargeIcons, treeImageList);
            treeList1.RowHeight = SysRuntime.Setting.NavMenuLargeIcons ? 32 : 24;
            SetDateTime();
            SetNetworkInfo();
            barController.PropertiesBar.LargeIcons = SysRuntime.Setting.MainPageToolbarLargeIcons;
        }

        private void mainNotifyIcon_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                btnMenuShowMain.PerformClick();
            }
            else if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                popupMenu1.ShowPopup(MousePosition);
            }
        }

        private void btnMenuShowMain_ItemClick(object sender, ItemClickEventArgs e)
        {
            this.Show();
        }

        private void btnMenuLock_ItemClick(object sender, ItemClickEventArgs e)
        {
            btnLock.PerformClick();
        }

        private void btnMenuExit_ItemClick(object sender, ItemClickEventArgs e)
        {
            btnExit.PerformClick();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            SetDateTime();
        }

        private void netWorkTimer_Tick(object sender, EventArgs e)
        {
            SetNetworkInfo();
        }

        private void ActiveUserTimer_Tick(object sender, EventArgs e)
        {
            SysRuntime.App.Active(SysRuntime.CurrentUser.Id);
        }

        private void lockTimer1_Tick(object sender, EventArgs e)
        {
            long noActiveTime = NativeMethods.GetLastInputTime();
            if (noActiveTime >= (SysRuntime.Setting.AutoLockInterval * 1000 * 60))
            {
                LockUser();
            }
        }

        private void TreeList1_NodesReloaded(object sender, EventArgs e)
        {
            moduleHelper.ExpandNode();
        }

        #region 属性

        private Dictionary<string, BaseDocument> _documents;

        protected Dictionary<string, BaseDocument> Documents
        {
            get { return _documents ?? (_documents = new Dictionary<string, BaseDocument>()); }
        }

        #endregion

        #region 方法

        private bool _modeuleInit;

        private void BindTreeData()
        {
            try
            {
                var modules = SysRuntime.GetUserModules();
                modules = modules?.Where(p => p.MenuFlag.HasValue && p.MenuFlag.Value == true).ToList();
                treeList1.DataSource = modules;
            }
            catch
            {
                MessageBoxHelper.ShowError("获取用户权限模块失败");
            }

            moduleHelper.InitModuleImageList(treeImageList, SysRuntime.Setting.NavMenuLargeIcons);
            
        }

        private void InitUserModules()
        {
            if (SysRuntime.Setting.IsDebugMode)
            {
                return;
            }

            List<SysModule> modules = (List<SysModule>) treeList1.DataSource;
            if (modules == null) return;
            _modeuleInit = true;
            foreach (var item in modules)
            {
                InitDocument(item);
            }
            _modeuleInit = false;
            mainTabbedView.Controller.CloseAll();
            Documents.Clear();
        }

        protected void LockUser()
        {
            this.lockTimer1.Enabled = false;
            this.Hide();
            var frm = new FrmUnLock();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                this.Show();
                if (this.WindowState != FormWindowState.Maximized)
                {
                    this.WindowState = FormWindowState.Maximized;
                }

                this.lockTimer1.Enabled = true;
            }

            frm.Dispose();
        }

        /// <summary>
        /// 添加文档
        /// </summary>
        public void InitDocument(SysModule entity)
        {
            if (entity == null) return;
            if (entity.Id.Equals("0")) return;
            if (string.IsNullOrEmpty(entity.WinProvider)) return;
            if (!entity.PreloadingFlag.HasValue || !entity.PreloadingFlag.Value) return;

            try
            {
                var frm = ObjectHelper.CreateInstance<Form>(entity.WinProvider);
                if (frm == null) return;
                frm.Text = entity.Name;
                frm.Tag = entity.Code;
                if (frm is FrmBase bform)
                {
                    bform.PreLoading = true;
                    bform.ParamDataString = entity.ParamData;
                }

                frm.MdiParent = this;
                frm.Show();
            }
            catch (Exception e)
            {
                DebugHelper.Catch(e);
            }
        }

        /// <summary>
        /// 添加文档
        /// </summary>
        public void AddDocument(SysModule entity)
        {
            if (entity == null) return;
            if (entity.Id.Equals("0")) return;
            if (string.IsNullOrEmpty(entity.WinProvider)) return;

            var code = entity.Code;
            var name = entity.Name;

            if (!Documents.TryGetValue(code, out var document))
            {
                var sw = new Stopwatch();
                sw.Start();
                try
                {
                    var frm = ObjectHelper.CreateInstance<Form>(entity.WinProvider);
                    if (frm == null)
                    {
                        sw.Stop();
                        barStaticItem1.Caption = $"耗时:{sw.Elapsed.TotalMilliseconds:###0.##} ms";
                        return;
                    }
                    frm.Text = name;
                    frm.Tag = code;
                    if (frm is FrmBase bform)
                    {
                        bform.ParamDataString = entity.ParamData;
                    }
                    if (entity.DialogFlag.HasValue && entity.DialogFlag.Value)
                    {
                        frm.ShowDialog();
                        frm.Dispose();
                    }
                    else
                    {
                        frm.MdiParent = this;
                        frm.Show();
                    }
                }
                finally
                {
                    sw.Stop();
                    barStaticItem1.Caption = $"耗时:{sw.Elapsed.TotalMilliseconds:###0.##} ms";
                }
            }
            else
            {
                mainTabbedView.Controller.Activate(document);
            }
        }

        public void AddDocument(string code, Form form)
        {
            if (string.IsNullOrEmpty(code)) return;

            if (!Documents.TryGetValue(code, out var document))
            {
                form.Tag = code;
                form.MdiParent = this;
                form.Show();
            }
            else
            {
                mainTabbedView.Controller.Activate(document);
            }
        }

        /// <summary>
        /// 单击树
        /// </summary>
        protected void TreeClick()
        {
            var entity = treeList1.GetDataRecordByNode(treeList1.FocusedNode);
            if (entity != null)
            {
                AddDocument(entity as SysModule);
            }
        }

        protected void SetDateTime()
        {
            this.statusTime.Caption = DateTimeHelper.FormatDateHasSecond(DateTime.Now);
        }

        protected void SetNetworkInfo()
        {
            //if (NetHelper.IsConnected())
            //{
            //    statusServer.Caption = "网络连接正常";
            //    //statusNetWork.Glyph = XCI.Auth.Properties.Resources.NetWork16;
            //}
            //else
            //{
            //    statusServer.Caption = "没有连接到网络";
            //    //statusNetWork.Glyph = XCI.Auth.Properties.Resources.NetWorkDis16;
            //}
            this.statusIP.Caption = NetHelper.GetLocalIP();
        }

        protected void SetStatusInfo()
        {
            if (SysRuntime.CurrentUser == null)
            {
                this.statusUser.Caption = null;
            }
            else
            {
                this.statusUser.Caption = string.Concat(SysRuntime.CurrentUser.Name, "(",
                    SysRuntime.CurrentUser.Account, ")", "@", SysRuntime.CurrentUser.DeptName);
            }

            this.statusOs.Caption = NativeMethods.GetWindowsName();
            this.statusServer.Caption = SysService.Instance.GetName();
        }

        #endregion

        #region 控件事件

        private void FrmStandardMain_Load(object sender, EventArgs e)
        {
            Text = SysRuntime.Setting.Title;
            moduleHelper = new ModuleHelper(treeList1);

            mainNotifyIcon.Icon = this.Icon;
            mainNotifyIcon.Visible = SysRuntime.Setting.ShowNotification;
            mainNotifyIcon.Text = this.Text;

            treeList1.ViewInfo.PaintAppearance.Empty.BackColor = BackColor;
            treeList1.ViewInfo.PaintAppearance.Row.BackColor = BackColor;

            SetStatusInfo();
            BindTreeData();
            InitUserModules();

            lockTimer1.Enabled = SysRuntime.Setting.AllowAutoLockMain;

            //Opacity = 100;

            navModule.Appearance.NavigationPaneHeader.Font = new Font(Font.Name, Font.Size + 1);

            TimerHelper.DelayExecuteWin(200, () =>
            {
                SplashHelper.CloseSplash();
                ShowInTaskbar = true;
                this.WindowState = FormWindowState.Maximized;
                navModule.OptionsNavPane.NavPaneState = NavPaneState.Expanded;
            });
        }

        private void StandardMainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!SysRuntime.Setting.CloseMainIsExit && !_isExitSystem)
            {
                this.Hide();
                e.Cancel = true;
            }
            else
            {
                if (MessageBoxHelper.ShowMessageYesNo("您确定要退出吗？") != System.Windows.Forms.DialogResult.Yes)
                {
                    e.Cancel = true;
                }
                else
                {
                    //SystemUserManage.Current.Logout(CurrentUserId);
                    mainNotifyIcon.Dispose();
                }
            }
        }

        private void StandardMainForm_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.F)
            {
                editSearchModule.Select();
                e.Handled = true;
            }
        }

        //private void editSearchModule_EditValueChanged(object sender, EventArgs e)
        //{
        //    treeList1.ApplyFindFilter(editSearchModule.Text.Trim());
        //}

        private void editSearchModule_ButtonClick(object sender,
            DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            var btn = editSearchModule.Properties.Buttons[0];
            btn.Enabled = false;
            //SystemPermissionHelper.RefreshUserPermissionCache();
            //CurrentUser.Modules = S.Module.QueryEnabled();
            SysRuntime.RefreshUserModules();
            BindTreeData();
            TimerHelper.DelayExecuteWin(5000, () => btn.Enabled = true);
        }

        //private void editSearchModule_KeyPress(object sender, KeyPressEventArgs e)
        //{
        //    if (e.KeyChar == 13)
        //    {
        //        e.Handled = true;
        //        TreeClick();
        //    }
        //}

        private void treeList1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                e.Handled = true;
                TreeClick();
            }
        }

        private void treeModule_Click(object sender, EventArgs e)
        {
            if (e is MouseEventArgs ev)
            {
                HitInfoType info = treeList1.CalcHitInfo(ev.Location).HitInfoType;
                if (info == HitInfoType.ColumnEdge || info == HitInfoType.Button || info == HitInfoType.Empty)
                {
                    return;
                }
            }

            TreeClick();
        }

        //private void treeList1_Load(object sender, EventArgs e)
        //{
        //    if (treeList1.Nodes.Count > 0)
        //    {
        //        treeList1.FocusedNode = treeList1.Nodes[0];
        //    }
        //}

        private void treeList1_GetStateImage(object sender, GetStateImageEventArgs e)
        {
            e.NodeImageIndex = moduleHelper.GetModuleImageIndex(e.Node);
        }

        private void mainTabbedView_DocumentAdded(object sender, DocumentEventArgs e)
        {
            if (_modeuleInit) return;
            if (e.Document?.Form?.Tag != null)
            {
                string code = e.Document.Form.Tag.ToString();
                if (!Documents.ContainsKey(code) && treeList1.FocusedNode != null)
                {
                    e.Document.Image =
                        treeImageList.Images[moduleHelper.GetModuleImageIndex(treeList1.FocusedNode)];
                    Documents.Add(code, e.Document);
                }
            }
        }

        private void mainTabbedView_DocumentClosing(object sender, DocumentCancelEventArgs e)
        {
            if (_modeuleInit) return;
            if (e.Document?.Form?.Tag != null)
            {
                var code = e.Document.Form.Tag.ToString();
                Documents.Remove(code);
            }
        }

        private void mainTabbedView_DocumentActivated(object sender, DocumentEventArgs e)
        {
            if (_modeuleInit)
            {
                return;
            }
            //if (e.Document?.Tag != null)
            //{
            //    string code = e.Document.Tag.ToString();
            //    var node = treeList1.FindNodeByFieldValue("Code", code);
            //    if (node != null)
            //    {
            //        node.Selected = true;
            //    }
            //}
        }

        private void btnSetting_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var frm = new FrmUserSetting();
            frm.ShowDialog();
            frm.Dispose();
            mainNotifyIcon.Visible = SysRuntime.Setting.ShowNotification;
            //formCaption.Visible = SysRuntime.Setting.MainPageShowCaption;
        }

        private void btnTheme_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var frm = new FrmNewTheme();
            frm.ShowDialog();
            frm.Dispose();
        }

        private void btnIme_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var frm = new FrmIme();
            frm.ShowDialog();
            frm.Dispose();
        }

        private void btnPassword_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var frm = new FrmModifyPassword();
            frm.ShowDialog();
            frm.Dispose();
        }

        private void btnLock_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.LockUser();
        }

        private void btnSwitchUser_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (MessageBoxHelper.ShowMessageYesNo("您确定要退出，更换其他账号登陆吗？") == System.Windows.Forms.DialogResult.Yes)
            {
                //SystemUserManage.Current.Logout(CurrentUserId);
                //this.Hide();
                AppHelper.ReLoginApplication();
            }
        }

        private void btnAbout_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var frmAbout = new FrmAbout();
            frmAbout.ShowDialog();
            frmAbout.Dispose();
        }

        private void btnExit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            _isExitSystem = true;
            //S.User.Logout(CurrentAccount);
            this.Close();
        }

        #endregion


    }
}